#include "StdAfx.h"
#include "DDSvrNetMan.h"
#include "stdio.h"

#include "..\DDPublic\DDSocket.h"

DDSvrNetMan::DDSvrNetMan(void)
{
#ifdef dkq_test_svrnet
	m_xLog.CreateLogDir("DDSvrNetSDK",0x1001);
#endif
}

DDSvrNetMan::~DDSvrNetMan(void)
{
	SvrStop();
}

int DDSvrNetMan::SvrStart()
{
	if( !CheckCallBack() )
	{
		return DD_ERR_CALLBACKREG;
	}

	m_xLoginMan.SetSvrNetMan(this);

	return DDListenThread::Start();
}

int DDSvrNetMan::SvrStop()
{
	DDListenThread::Stop();

	m_xLoginMan.UnInitialize();	

	return DD_ERR_SUCCESS;
}

int DDSvrNetMan::vDispatch(SOCKET hClientSocket,NET_DATA_HEAD *pDataHead,BYTE *pBuffer)
{
	int nRet = DD_ERR_SUCCESS;

	NET_DATA_HEAD  xReturnHead;
	NET_DATA_HEAD *pReturnHead = &xReturnHead;

	xReturnHead = *pDataHead;
	pReturnHead->nDataType  += 1;
	pReturnHead->lDataSize  = 0;

#ifdef dkq_test_svrnet
	//((DDSvrNetMan*)this)->m_xLog.WriteLog(__FILE__,__LINE__,"in nMsgType:%d",pMsgHead->nMsgType);
#endif

	switch( pDataHead->nDataType )
	{
	case DataType_Login:
		{		
			nRet = m_xLoginMan.Login(pDataHead,pBuffer,hClientSocket);
		}
		break;
	default:
		{
			nRet = DD_ERR_FAILURE;
		}
		break;
	}

#ifdef dkq_test_svrnet
	//((DDSvrNetMan*)this)->m_xLog.WriteLog(__FILE__,__LINE__,"out nMsgType:%d",pMsgHead->nMsgType);
#endif

	if( DD_ERR_SUCCESS != nRet )
	{
		pReturnHead->nAckErrCode = nRet;

		DWORD dwRet = 0;
		DDSendDataS(hClientSocket,(char*)pReturnHead,
			sizeof(NET_DATA_HEAD),
			&dwRet,
			DDListenThread::m_hWSASendRecvEvent,
			DDListenThread::m_hWSAExitEvent,DD_WAITTIME);

		//Sleep(50);

		DDShutDownSocket( hClientSocket );
		DDCloseSocket( hClientSocket );
		hClientSocket = NULL;
	}

	return nRet;
}

